//
//  ChooseThemeViewController.m
//  leo
//
//  Created by 常艳 on 15/9/19.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "ChooseThemeViewController.h"
#import "LeoMsg.h"
#import "GrowDataManager.h"
#import "DataManager.h"
#import "AppDelegate.h"
#import "SyncManager.h"
@interface ChooseThemeViewController ()
@property(nonatomic,strong) NSArray *themeData;
@property(nonatomic,strong) NSString *selectThemeid;
@property(nonatomic,strong) NSString *currentSelectThemeid;
@property(nonatomic,assign) BOOL isRegis;
@property(nonatomic,assign) float rate;
@property(nonatomic,strong) GrowDataManager *growDataManager;
@property(nonatomic,strong) DataManager *dataManager;
@property(nonatomic,strong) Watch *selectWatch;

@end

@implementation ChooseThemeViewController
@synthesize themeData;
@synthesize rate;
@synthesize growDataManager;
@synthesize isRegis;
@synthesize selectThemeid;
@synthesize dataManager;
@synthesize selectWatch;
@synthesize currentSelectThemeid;
-(void)dealloc
{
    themeData=NULL;
    growDataManager=NULL;
    dataManager=NULL;
    selectWatch=NULL;
    selectThemeid=NULL;
    currentSelectThemeid=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.extendedLayoutIncludesOpaqueBars=YES;
    self.title=@"选择成长主题";
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate!=NULL)
    {
        if(mydelegate.isAdmin==NO)
        {
            
        }
        else
        {
            UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(saveTheme)];
            [self.navigationItem setRightBarButtonItem:rightButton];
            rightButton=NULL;
        }
    }

    CGRect r=[ UIScreen mainScreen ].applicationFrame;
    rate=r.size.width/320;
    isRegis=NO;
    [self.table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.table.showsVerticalScrollIndicator=NO;
    self.table.backgroundColor=[UIColor clearColor];
    
    growDataManager=[[GrowDataManager alloc] init];
    if(growDataManager==NULL)
        return;
    themeData=[growDataManager getThemes];

    dataManager=[[DataManager alloc] init];
    if(dataManager==NULL)
        return;
    User *user=[User sharedSingleton];
    if(user==NULL)
        return;
    selectWatch=[dataManager getActiveWatch:user.uid];
    selectThemeid=selectWatch.themeId;
    currentSelectThemeid=selectWatch.themeId;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(themeData!=NULL)
        return themeData.count;
    else
        return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"theme";
    NSInteger row=[indexPath row];
        if(!self.isRegis)
        {
            [tableView registerNib:[UINib nibWithNibName:@"ThemeTableViewCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
            self.isRegis=YES;
        }
        
        ThemeTableViewCell *cell = (ThemeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        cell.backgroundColor=[UIColor clearColor];
        cell.userInteractionEnabled=YES;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        if(themeData!=NULL)
        {
            Theme *theme=[themeData objectAtIndex:row];
            if(theme==NULL)
            {
                NSLog(@"%@,theme is null.",choosetheme_tag);
            }
            else
            {
                cell.titleLable.text=theme.name;
                UIImage *img;
                if([theme.themeId isEqualToString:selectThemeid])
                {
                    img=[UIImage imageNamed:theme.themePicUrl];
                    
                }
                else
                {
                    img=[UIImage imageNamed:theme.unablePicUrl];
                }
                cell.headImg.image=img;
                cell.titleImg.image=[UIImage imageNamed:theme.labPicUrl];
            }
        }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 209.0f*self.rate;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate!=NULL)
    {
        if(mydelegate.isAdmin==NO)
            return;
    }
    Theme *theme=[themeData objectAtIndex:[indexPath row]];
    if(theme==NULL)
    {
        NSLog(@"%@,didSelectRowAtIndexPath,theme is null.",choosetheme_tag);
    }
    else
    {
        currentSelectThemeid=theme.themeId;
        if([selectThemeid isEqualToString:currentSelectThemeid])
            return;
        [self showAlert];
    }
    
    
}

-(void)showAlert
{
    NSString *title=NULL;
    if([currentSelectThemeid isEqualToString:@"1"])
    {
        title=@"是否将成长中心切换成玩具总动员?";
    }
    else
    {
        title=@"是否将成长中心切换成小熊维尼?";
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:title
                                                   delegate:self
                                          cancelButtonTitle:@"否"
                                          otherButtonTitles:@"是",nil];
    [alert show];
    alert=nil;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex==1)
    {
        selectThemeid=currentSelectThemeid;
        [self.table reloadData];
    }
}

-(void)saveTheme
{
    SyncManager *syncManager=[[SyncManager alloc] init];
    if(syncManager==NULL||selectWatch==NULL||growDataManager==NULL)
    {
        [LeoMsg showToastMsg:@"设置主题发生错误" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
        return;
    }
    NSString *watchParams=[NSString stringWithFormat:@"{\"themeId\":%@,\"wpLevel\":%d}",currentSelectThemeid,selectWatch.watchTheme];
    [syncManager sendCommand:selectWatch.deviceUid type:THEME_CHANGE watchParams:watchParams completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if(result==SUCESS)
        {
            [growDataManager setTheme:selectWatch.deviceUid themeId:selectThemeid];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [Tooler showHttpToast:result description:description msg:@"设置主题失败" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
        }
    }];

}

@end
